<template>
    <div class="container">
        <div class="main">
            <div class="header">
                <el-button type="primary" @click="openDialog(add)">新建</el-button>
                <el-button type="success" @click="importData">导入</el-button>
                <el-button type="danger" @click="batchDelete">批量删除</el-button>
                <el-select v-model="selectedFilter" @change="handleFilterChange">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>
                <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
                <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
                <el-button type="info" @click="reset">重置</el-button>
            </div>
            <el-table :empty-text="emptyText" :data="tableData" border class="eltable"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="zjqx_id" v-if="false"></el-table-column>
                <el-table-column prop="zjqx_code" label="缺陷编码" width="200"></el-table-column>
                <el-table-column prop="zjqx_name" label="缺陷名称"></el-table-column>
                <el-table-column prop="zjqx_fl" v-if="false"></el-table-column>
                <el-table-column prop="zjqx_fl_name" label="缺陷类型"></el-table-column>
                <el-table-column prop="zjqx_cpfl" v-if="false"></el-table-column>
                <el-table-column prop="zjqx_cpfl_name" label="缺陷类型" width="400"></el-table-column>
                <el-table-column prop="zjqx_remark" label="备注" width="400"></el-table-column>
                <el-table-column label="启用" width="70">
                    <template #default="{ row }">
                        <el-switch v-model="row.zjqx_state" :active-value="1" :inactive-value="0"
                            @change="updateState(row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                        <!-- <el-button type="text" @click="openDialog(sc)">查看</el-button> -->
                        <el-button type="text" @click="openDialog(row)">编辑</el-button>
                        <el-button type="text" @click="deleteRow(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900px" @close="resetForm" :append-to-body="true">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="缺陷编码" prop="zjqx_code">
                            <el-input v-model="formData.zjqx_code" :readonly="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="缺陷名称：" prop="zjqx_name">
                            <el-input v-model="formData.zjqx_name" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="缺陷类型：" prop="zjqx_fl">
                            <el-select v-model="formData.zjqx_fl" placeholder="请选择属性">
                                <el-option v-for="item in TYPEOptions" :key="item.dictionary_id"
                                    :label="item.dictionary_name" :value="item.dictionary_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注：" prop="zjqx_remark">
                            <el-input v-model="formData.zjqx_remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="24">
                        <el-form-item label="适用产品：" prop="zjqx_cpfl">
                            <el-table :data="CPtableData" border class="eltable" style="height: 200px;">
                                <el-table-column type="index" label="序号" width="60"></el-table-column>
                                <el-table-column prop="dictionary_code" label="产品编码"></el-table-column>
                                <el-table-column prop="dictionary_name" label="产品名称"></el-table-column>
                                <el-table-column label="操作" width="60">
                                    <template #default="{ row }">
                                        <el-button type="text" @click="deleteProduct(row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="button-container">
                                <el-button class="add-btn" @click="openProductDialog" type="text">+</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>

            <!-- 嵌套的产品选择弹窗 -->
            <el-dialog v-model="isCPFLMTKVisible" title="选择产品"
                style="height: 600px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
                <CPFLMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection">
                </CPFLMTK>
            </el-dialog>

        </el-dialog>

    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import CPFLMTK from '../MTK/CPFLMTK.vue';


export default {
    components: { CPFLMTK },
    setup() {
        const emptyText = '暂无数据';
        const selectedFilter = ref('1');
        const searchTable = ref('');
        const tableData = ref([]);
        const CPtableData = ref([]);
        const multipleSelection = ref([]);
        const dialogVisible = ref(false);
        const dialogTitle = ref('新增质检缺陷');
        const formRef = ref(null);
        const formData = ref({
            zjqx_code: '',
            zjqx_name: '',
            zjqx_fl: null,
            zjqx_remark: '',
            zjqx_cpfl: '',
        });
        const isCPFLMTKVisible = ref(false);
        const dictionary_code = ref([]);

        const TYPEOptions = ref([]);

        const formRules = {
            zjqx_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
            zjqx_fl: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
            zjqx_cpfl: [{
                validator: (_, __, callback) => {
                    if (CPtableData.value.length === 0) {
                        callback(new Error('至少需要添加一个适用产品'));
                    } else {
                        callback();
                    }
                },
                trigger: 'blur'
            }]
        };

        const fetchTableData = () => {
            axios.get(`/api/QMS_ZJQX/GetQMS_ZJQX?state=${selectedFilter.value}`)
                .then(res => {
                    tableData.value = res.data;
                })
                .catch(err => {
                    console.error('Error fetching data:', err);
                    ElMessage.error('加载数据失败，请稍后再试');
                });
        };

        const fetchCPTableData = (zjqx_cpfl) => {
            if (!zjqx_cpfl || zjqx_cpfl.trim() === '') {
                CPtableData.value = [];
                return;
            }
            axios.get(`/api/Dict/GetDict_Codes?type=7&codes=${zjqx_cpfl}`)
                .then(res => {
                    if (Array.isArray(res.data)) {
                        CPtableData.value = res.data;
                    } else {
                        console.error('Invalid data format:', res.data);
                        ElMessage.error('数据格式错误');
                    }
                })
                .catch(err => {
                    console.error('Error fetching data:', err);
                    ElMessage.error('加载数据失败，请稍后再试');
                });
        };


        // 选中行变化
        const handleSelectionChange = (val) => {
            multipleSelection.value = val;
        };

        // 筛选条件变化
        const handleFilterChange = () => {
            fetchTableData();
        };

        // 更新状态
        const updateState = (row) => {
            ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.put(`/api/QMS_ZJQX/StateChange?id=${row.zjqx_id}&state=${row.zjqx_state}`)
                    .then(response => {
                        if (response.data === true) {
                            ElMessage.success('状态已更新');
                        } else {
                            ElMessage.error('更新失败，后端返回错误');
                        }
                        fetchTableData();
                    })
                    .catch(err => {
                        console.error('Error:', err);
                        ElMessage.error('更新失败');
                    });
            }).catch(() => {
                fetchTableData();
                ElMessage.info('已取消改变');
            });
        };

        // 查询
        const query = () => {
            searchTableData(); // 假设后端支持关键字搜索，需传递searchTable.value
        };

        const searchTableData = () => {
            if (!searchTable.value) {
                fetchTableData();
                return;
            }
            const params = {
                state: selectedFilter.value,
                str: searchTable.value
            };
            axios.get('/api/QMS_ZJQX/GetQMS_ZJQX', { params })
                .then(res => {
                    tableData.value = res.data;
                })
                .catch(err => {
                    console.error('Error fetching data:', err);
                    ElMessage.error('加载数据失败，请稍后再试');
                });
        };

        // 重置
        const reset = () => {
            searchTable.value = '';
            selectedFilter.value = '1';
            fetchTableData();
        };

        // 删除单行
        const deleteRow = (row) => {
            ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.put(`/api/QMS_ZJQX/DelQMS_ZJQX?id=${row.zjqx_id}`)
                    .then(response => {
                        if (response.data === true) {
                            ElMessage.success("删除成功");
                            fetchTableData();
                        } else {
                            ElMessage.error("删除失败：后端返回失败");
                        }
                    })
                    .catch(err => {
                        console.error('删除失败:', err);
                        ElMessage.error("删除失败：请求异常");
                    });
            }).catch(() => {
                ElMessage.info("已取消删除");
            });
        };

        const batchDelete = async () => {
            if (multipleSelection.value.length === 0) {
                ElMessage.warning("请先选择要删除的项");
                return;
            }
            try {
                await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                const selectedIds = multipleSelection.value.map(item => item.zjqx_id); // 确保 zjqx_id 是后端需要的字段
                const response = await axios.put('/api/QMS_ZJQX/DelQMS_ZJQXs', selectedIds, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                if (response.data === true) {
                    ElMessage.success("批量删除成功");
                    fetchTableData();
                } else {
                    ElMessage.error("批量删除失败：后端返回失败");
                }
            } catch (error) {
                if (error !== 'cancel') {
                    ElMessage.error("批量删除失败");
                } else {
                    ElMessage.info("已取消批量删除");
                }
            }
        };

        const openDialog = async (row) => {
            await fetchTYPE(); // 确保加载缺陷类型

            if (row) {
                // 编辑操作
                dialogTitle.value = '编辑质检缺陷';
                formData.value = { ...row };
                await fetchCPTableData(row.zjqx_cpfl);
            } else {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
                const day = String(now.getDate()).padStart(2, '0'); // 补零

                // 生成四位随机数
                const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

                // 拼接时间字符串和随机数
                const formattedTime = `${year}${month}${day}`;
                let code = `ZJQX${formattedTime}${randomNumber}`;

                // 新增操作：彻底重置所有字段和表格
                dialogTitle.value = '新增质检缺陷';
                formData.value = {
                    zjqx_code: code,
                    zjqx_name: '',
                    zjqx_fl: null,
                    zjqx_remark: '',
                    zjqx_cpfl: '',    // 确保包含所有字段
                };
                CPtableData.value = [];
            }

            formData.value.zjqx_cpfl = CPtableData.value.length > 0 ? 'valid' : '';

            dialogVisible.value = true;
        };

        const submitForm = async () => {
            try {
                await formRef.value.validate(); // 验证表单

                // 获取 CPtableData 中的 cp_code，拼接成 (code1,code2) 格式
                const cpCodes = CPtableData.value.map(item => item.dictionary_code).join(',');
                formData.value.zjqx_cpfl = `${cpCodes}`;

                console.log(formData.value);
                let response;
                if (formData.value.zjqx_id) {
                    // 编辑模式，调用更新 API
                    response = await axios.put('/api/QMS_ZJQX/UpdateQMS_ZJQX', {
                        ...formData.value,
                    });
                } else {
                    // 新增模式，调用新增 API
                    response = await axios.post('/api/QMS_ZJQX/AddQMS_ZJQX', {
                        ...formData.value,
                        zjqx_id: 0, // 新增时 zjqx_id 设为 0
                        zjqx_state: formData.value.zjqx_state || 0, // 默认状态
                    });
                }

                if (response.data) {
                    ElMessage.success(formData.value.zjqx_id ? '编辑成功' : '新增成功');
                    dialogVisible.value = false;
                    fetchTableData(); // 刷新表格数据
                } else {
                    ElMessage.error('操作失败：后端返回失败');
                }
            } catch (err) {
                console.error('操作失败:', err);
                ElMessage.error('操作失败');
            }
        };

        // 获取物料分类
        const fetchTYPE = async () => {
            try {
                const response = await axios.get('/api/Dict/GetOneDict?id=19');
                TYPEOptions.value = response.data; // 正确赋值给TYPEOptions
                console.log(TYPEOptions.value);
            } catch (error) {
                console.error('获取项目属性失败:', error);
                ElMessage.error('获取项目属性失败，请稍后再试');
            }
        };


        // 选择产品  
        const handleSelectionConfirmed = async (codes) => {
            try {
                const response = await axios.get(`/api/Dict/GetDict_Codes`, {
                    params: {
                        type: 7,
                        codes: codes.join(',') // 关键修改：批量请求
                    }
                });
                if (Array.isArray(response.data)) {
                    CPtableData.value = response.data;
                } else {
                    ElMessage.error('数据格式错误');
                }
            } catch (error) {
                console.error('加载失败:', error);
                ElMessage.error('加载产品分类失败');
            } finally {
                isCPFLMTKVisible.value = false;
            }
        };

        //关闭产品模态框
        const handleCancelSelection = () => {
            isCPFLMTKVisible.value = false;
        };

        const openProductDialog = async () => {
            isCPFLMTKVisible.value = !isCPFLMTKVisible.value; // 切换显示状态  

        };


        // 在删除产品的逻辑中
        const deleteProduct = (row) => {
            CPtableData.value.splice(row, 1);
            formData.value.zjqx_cpfl = CPtableData.value.length > 0 ? 'valid' : '';
        };


        const resetForm = () => {
            formRef.value.resetFields();
        };

        onMounted(() => {
            fetchTYPE();
            fetchTableData();
        });

        return {
            TYPEOptions,
            fetchTYPE,
            searchTableData,
            handleSelectionChange,
            handleFilterChange,
            updateState,
            query,
            reset,
            deleteRow,
            batchDelete,
            emptyText,
            selectedFilter,
            searchTable,
            tableData,
            CPtableData,
            multipleSelection,
            dialogVisible,
            dialogTitle,
            formRef,
            formData,
            formRules,
            fetchTableData,
            openDialog,
            submitForm,
            resetForm,
            deleteProduct,
            openProductDialog,
            isCPFLMTKVisible,
            handleSelectionConfirmed,
            handleCancelSelection,
        };
    },
};
</script>

<style scoped>
.container {
    display: flex;
    gap: 20px;
    height: 95%;
}

.sidebar {
    height: 100%;

}

.main {
    width: 80%;
    flex: 1;
    height: 100%;
}

.header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}

.eltable {
    height: 95%;
}

.letree {
    height: 100%;
}

.demo-form-inline .el-input {
    --el-input-width: 200px;
}

.demo-form-inline .el-select {
    --el-select-width: 200px;
}

.el-button--text {
    font-size: 16px;
    /* 调整按钮字体大小 */
    color: #409EFF;
    /* 调整按钮颜色 */
    padding: 0;
    /* 去掉内边距 */
}

.button-container {
    text-align: right;
    margin-top: 10px;
    margin-left: 48%;
}

.add-btn {
    font-size: 24px;
    padding: 0 15px;
    vertical-align: middle;
}

.el-dialog__wrapper {
    z-index: 2000;
    /* 确保嵌套弹窗的层级高于主弹窗 */
}

.el-overlay {
    z-index: 2000 !important;
}

.el-dialog {
    z-index: 2001 !important;
}
</style>